package com.example.sprintboot.controller;

import com.example.sprintboot.entity.User;
import com.example.sprintboot.security.UserDetailsImpl;
import com.example.sprintboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private final UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserController(@Autowired UserService userService) {
        this.userService = userService;
    }

    /**
     * 获取当前登录用户ID
     */
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) authentication.getPrincipal()).getUserId();
        }
        return null;
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/profile")
    public Map<String, Object> getProfile() {
        Map<String, Object> result = new HashMap<>();
        Integer userId = getCurrentUserId();
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return result;
        }
        User user = userService.selectUserById(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        result.put("success", true);
        Map<String, Object> data = new HashMap<>();
        data.put("nickname", user.getNickname());
        data.put("phone", user.getPhone());
        data.put("email", user.getEmail());
        result.put("data", data);
        return result;
    }

    /**
     * 修改当前用户信息
     */
    @PutMapping("/profile")
    public Map<String, Object> updateProfile(@RequestBody Map<String, String> req) {
        Map<String, Object> result = new HashMap<>();
        Integer userId = getCurrentUserId();
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return result;
        }
        User user = userService.selectUserById(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        user.setNickname(req.getOrDefault("nickname", user.getNickname()));
        user.setPhone(req.getOrDefault("phone", user.getPhone()));
        user.setEmail(req.getOrDefault("email", user.getEmail()));
        userService.updateUser(user);
        result.put("success", true);
        result.put("message", "修改成功");
        return result;
    }

    /**
     * 修改当前用户密码
     */
    @PutMapping("/password")
    public Map<String, Object> changePassword(@RequestBody Map<String, String> req) {
        Map<String, Object> result = new HashMap<>();
        Integer userId = getCurrentUserId();
        if (userId == null) {
            result.put("success", false);
            result.put("message", "用户未登录");
            return result;
        }
        User user = userService.selectUserById(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        String oldPwd = req.get("oldPassword");
        String newPwd = req.get("newPassword");
        if (oldPwd == null || newPwd == null) {
            result.put("success", false);
            result.put("message", "参数错误");
            return result;
        }
        if (!passwordEncoder.matches(oldPwd, user.getPassword())) {
            result.put("success", false);
            result.put("message", "原密码错误");
            return result;
        }
        user.setPassword(passwordEncoder.encode(newPwd));
        userService.updateUser(user);
        result.put("success", true);
        result.put("message", "密码修改成功");
        return result;
    }

    @GetMapping("/list")
    public List<User> list() {
        return userService.selectAllUsers();
    }

    @PostMapping
    public boolean save(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @PutMapping("/{userId}")
    public boolean update(@PathVariable Integer userId, @RequestBody User user) {
        user.setUserId(userId);
        return userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public boolean removeById(@PathVariable Integer id) {
        return userService.deleteUserById(id);
    }

    @GetMapping("/{id}")
    public User selectUserById(@PathVariable Integer id) {
        return userService.selectUserById(id);
    }

    @PostMapping("/register")
    public User register(@RequestBody User user) {
        return userService.register(user);
    }
}